package com.cg.global;

import com.cg.annotation.Decrypt;
import com.cg.config.EncryptProperties;
import com.cg.utils.AESUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

@ControllerAdvice
@RequiredArgsConstructor
public class DecryptRequest implements RequestBodyAdvice {

    private final EncryptProperties encryptProperties;

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.hasMethodAnnotation(Decrypt.class);
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {

        byte[] body = new byte[httpInputMessage.getBody().available()];
        httpInputMessage.getBody().read(body);
        try {
            //使用AES/CBC/PKCS5Padding加密
            String decrypt = AESUtils.decrypt(new String(body), encryptProperties.getKey());
            final ByteArrayInputStream bais = new ByteArrayInputStream(decrypt.getBytes());
            return new HttpInputMessage() {
                public InputStream getBody() throws IOException {
                    return bais;
                }

                public HttpHeaders getHeaders() {
                    return httpInputMessage.getHeaders();
                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpInputMessage;
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }
}
